<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="代码在线预览" @ok="handleSubmit" @cancel="handleCancel" destroyOnClose 
    :defaultFullscreen="true">
    <a-row :class="['p-0']" >
      <a-col :span="6" style="margin-bottom: 2px; overflow-x: hidden; overflow-y:auto">
        <PreviewCodeLeftTree ref="leftTree" :treeData="treeData" v-model:selectedKeys="selectedKeys" />
      </a-col>
      <a-col :span="18" style="margin-bottom: 10px; overflow-x: hidden; overflow-y:auto">
        <MyAceEditor ref="editor" :style="aceEditorStyle" :readOnly="true"/>
      </a-col>
    </a-row>
  </BasicModal>
</template>

<script lang="ts" setup>
  import {BasicModal, useModalInner} from '/@/components/Modal';
  import PreviewCodeLeftTree from './PreviewCodeLeftTree.vue';
  import MyAceEditor from '/@/components/My/MyAceEditor.vue';
  import {getInfo, update} from '../codeGen.api';
  import {TreeData} from './type';
  import { ref, watch, reactive, onMounted } from 'vue';
  const activeKey = ref('-1')
  const rowId = ref('');
  const editor = ref()
  const aceEditorStyle = ref<String>("width: 100%; height: calc(100vh - 200px)")
  const leftTree = ref();  

  const treeData = ref<TreeData[]>([]);

  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    // await resetGenInfoFields();
    setModalProps({confirmLoading: false, minHeight:80});
    activeKey.value = '1'
		console.log("data: ", data.list)
    treeData.value = data.list
		if (treeData.value.length > 0) {
      editor.value.updateEditor({
        readOnly: true, mode: getEditorMode(treeData.value[0].title), value: treeData.value[0].content
      })
		}
		console.log("treeData: ", treeData)
  });

  const selectedKeys = ref([])

  const getEditorMode = (fileName) => {
    let mode = 'java'
    const ext = fileName.substring(fileName.lastIndexOf('.') + 1)
    if (ext === 'java') mode = 'java'
    else if(ext === 'xml') mode = 'xml'
    else if(ext === 'js') mode = 'javascript'
    else if(ext === 'sql') mode = 'sql'
    else if(ext === 'vm') mode = 'velocity'
    else if(ext === 'json') mode = 'json'
    else mode = 'text'
    return mode
  }

  watch(
    () => selectedKeys,
    (keys: any) => {
			keys.value.forEach(key => {
				treeData.value.forEach(v => {
					if (v.key === key) {
            editor.value.updateEditor({
              readOnly: true, mode: getEditorMode(v.title), value: v.content
            })
						console.log("keys: ", keys.value)
					}
				})
			})
    },
		{ deep: true, immediate: true }
  )

  onMounted(() => {
		
  })

  //表单提交事件
  async function handleSubmit(e) {
    try {
      //刷新列表
      // emit('success', {isUpdate: unref(isUpdate), values: {...values, id: rowId.value}});
    } finally {
      closeModal();
      setModalProps({confirmLoading: false});
    }
  }

  const handleCancel = (e) => {
    editor.value.reset()
  }

	
</script>